package com.ljtxxhwj.myblob.controller;

import com.ljtxxhwj.myblob.entity.Favorite;
import com.ljtxxhwj.myblob.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/favorites")
public class FavoriteController {

    private final FavoriteService favoriteService;

    @Autowired
    public FavoriteController(FavoriteService favoriteService) {
        this.favoriteService = favoriteService;
    }

    // 根据用户ID查询该用户收藏的所有文章
    @GetMapping("/user/{userId}.do")
    public List<Favorite> getFavoritesByUserId(@PathVariable Integer userId) {
        return favoriteService.getFavoritesByUserId(userId);
    }

    // 根据文章ID查询收藏该文章的所有用户
    @GetMapping("/article/{articleId}.do")
    public List<Favorite> getFavoritesByArticleId(@PathVariable Integer articleId) {
        return favoriteService.getFavoritesByArticleId(articleId);
    }

    // 插入一个新的收藏记录
    @PostMapping("/{articleId}/favorite.do")
    public ResponseEntity<String> addFavorite(@PathVariable Integer articleId, @RequestBody Favorite favorite) {
        favorite.setArticleId(articleId);
        favorite.setFavoriteTime(LocalDateTime.now());
        try {
            favoriteService.addFavorite(favorite);
            return new ResponseEntity<>("Favorite added successfully", HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>("Error adding favorite", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据文章ID和用户ID删除收藏记录
    @DeleteMapping("/{articleId}/favorite/{userId}.do")
    public ResponseEntity<String> removeFavoriteByArticleAndUser(@PathVariable Integer articleId, @PathVariable Integer userId) {
        try {
            favoriteService.removeFavoriteByArticleAndUser(articleId, userId);
            return new ResponseEntity<>("Favorite removed successfully", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("Error removing favorite", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}